<script setup lang="ts">
import { reactive, ref } from "vue";
// import { uploadFileApi } from "@/api/system";
import { message } from "@/utils/message";
import {
  type UserInfo,
  getUserOneselfShowApi,
  updateUserOneselfApi,
  getDeptListApi,
  getJobTitleListApi,
  getRbacRoleListApi
} from "@/api/user";
import type { FormInstance, FormRules } from "element-plus";
import ReCropperPreview from "@/components/ReCropperPreview";
import { createFormData, deviceDetection } from "@pureadmin/utils";
import uploadLine from "@iconify-icons/ri/upload-line";

defineOptions({
  name: "Profile"
});

const imgSrc = ref("");
const cropperBlob = ref();
const cropRef = ref();
const uploadRef = ref();
const isShow = ref(false);
const userInfoFormRef = ref<FormInstance>();
const higherDeptOptions = ref();
const jobSelectOptions = ref();
const genderOptions = ref([
  {
    id: 1,
    name: "男"
  },
  {
    id: 2,
    name: "女"
  }
]);
const statusOptions = ref([
  {
    id: 1,
    name: "启用"
  },
  {
    id: 2,
    name: "禁用"
  }
]);
const isSuperAdminOptions = ref([
  {
    id: 0,
    name: "否"
  },
  {
    id: 1,
    name: "是"
  }
]);
const roleIdsOptions = ref();
const userInfos = reactive({
  userId: "",
  id: "",
  avatar: "",
  username: "",
  name: "",
  email: "",
  phone: "",
  remarks: "",
  departmentId: "",
  entryDate: "",
  jobTitleId: "",
  gender: "",
  status: "",
  isSuperAdmin: "",
  roleIds: "",
  password: ""
});

const rules = reactive<FormRules<UserInfo>>({
  username: [{ required: true, message: "用户名必填", trigger: "blur" }],
  name: [{ required: true, message: "用户名必填", trigger: "blur" }]
});

function queryEmail(queryString, callback) {
  const emailList = [
    { value: "@qq.com" },
    { value: "@126.com" },
    { value: "@163.com" }
  ];
  let results = [];
  let queryList = [];
  emailList.map(item =>
    queryList.push({ value: queryString.split("@")[0] + item.value })
  );
  results = queryString
    ? queryList.filter(
        item =>
          item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      )
    : queryList;
  callback(results);
}

const onChange = uploadFile => {
  const reader = new FileReader();
  reader.onload = e => {
    imgSrc.value = e.target.result as string;
    isShow.value = true;
  };
  reader.readAsDataURL(uploadFile.raw);
};

const handleClose = () => {
  cropRef.value.hidePopover();
  uploadRef.value.clearFiles();
  isShow.value = false;
};

const onCropper = ({ blob }) => (cropperBlob.value = blob);

const handleSubmitImage = () => {
  const formData = createFormData({
    files: new File([cropperBlob.value], "avatar")
  });
  // uploadFileApi(formData)
  //   .then(({ success, result }) => {
  //     if (success) {
  //       message("更新头像成功", { type: "success" });
  //       handleClose();
  //     } else {
  //       message("更新头像失败");
  //     }
  //   })
  //   .catch(error => {
  //     message(`提交异常 ${error}`, { type: "error" });
  //   });
};

// 更新信息
const onSubmit = async (formEl: FormInstance) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      userInfos.userId = userInfos.id;
      updateUserOneselfApi(userInfos)
        .then(res => {
          if (res.code === 200) {
            message("更新信息成功", { type: "success" });
          }
        })
        .catch(error => {
          console.log(error);
          message(error.response.data.msg ?? "操作失败,请联系管理员", {
            type: "error"
          });
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

getUserOneselfShowApi().then(res => {
  Object.assign(userInfos, res.result);
});
// getDeptListApi().then(res => {
//   higherDeptOptions.value = res.result;
// });
// getJobTitleListApi().then(res => {
//   jobSelectOptions.value = res.result;
// });
// getRbacRoleListApi({ page: 1, perPage: 999 }).then(res => {
//   roleIdsOptions.value = res.result.list;
// });
</script>

<template>
  <div
    :class="[
      'min-w-[180px]',
      deviceDetection() ? 'max-w-[100%]' : 'max-w-[70%]'
    ]"
  >
    <h3 class="my-8">个人信息</h3>
    <el-form
      ref="userInfoFormRef"
      :rules="rules"
      :model="userInfos"
      label-width="auto"
    >
      <!-- <el-form-item label="头像">
        <el-avatar :size="80" :src="userInfos.avatar" v-if="userInfos.avatar"/>
        <el-avatar :size="80" src="/src/assets/user.jpg" v-else/>
        <el-upload
          ref="uploadRef"
          accept="image/*"
          action="#"
          :limit="1"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onChange"
        >
          <el-button plain class="ml-4">
            <IconifyIconOffline :icon="uploadLine" />
            <span class="ml-2">更新头像</span>
          </el-button>
        </el-upload>
      </el-form-item> -->
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="userInfos.username"
          placeholder="请输入用户名"
          disabled
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="userInfos.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userInfos.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="归属部门" v-if="userInfos.department">
        <!-- <el-cascader
          v-model="userInfos.departmentId"
          class="w-full"
          :options="higherDeptOptions"
          :props="{
            value: 'id',
            label: 'name',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          filterable
          placeholder="请选择归属部门"
          disabled
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader> -->
        <el-input
          v-model="userInfos.department.name"
          placeholder="请输入"
          clearable
          disabled
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-autocomplete
          v-model="userInfos.email"
          :fetch-suggestions="queryEmail"
          :trigger-on-focus="false"
          placeholder="请输入邮箱"
          clearable
          class="w-full"
          disabled
        />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input
          v-model="userInfos.phone"
          placeholder="请输入联系电话"
          clearable
          disabled
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="userInfos.gender"
          placeholder="请选择性别"
          class="w-full"
          clearable
        >
          <el-option
            v-for="(item, index) in genderOptions"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入职时间" prop="entryDate">
        <el-date-picker
          v-model="userInfos.entryDate"
          type="date"
          placeholder="请选择入职时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
          disabled
        />
      </el-form-item>
      <el-form-item label="职位" prop="jobTitleId">
        <el-select
          v-model="userInfos.jobTitleId"
          placeholder="请选择职位"
          class="w-full"
          clearable
          disabled
        >
          <el-option
            v-for="(item, index) in jobSelectOptions"
            :key="index"
            :label="item.name"
            :value="item.jobTitleId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="超级管理员" prop="isSuperAdmin">
        <el-select
          v-model="userInfos.isSuperAdmin"
          placeholder="请选择是否为超级管理员"
          class="w-full"
          clearable
          disabled
        >
          <el-option
            v-for="(item, index) in isSuperAdminOptions"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="角色" prop="roleIds">
        <el-select
          v-model="userInfos.roleIds"
          placeholder="请选择角色"
          class="w-full"
          clearable
          multiple
          :multiple-limit="1"
          disabled
        >
          <el-option
            v-for="(item, index) in roleIdsOptions"
            :key="index"
            :label="item.name"
            :value="item.roleId"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="userInfos.status"
          placeholder="请选择状态"
          class="w-full"
          clearable
          disabled
        >
          <el-option
            v-for="(item, index) in statusOptions"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="userInfos.remarks"
          placeholder="请输入备注"
          type="textarea"
          :autosize="{ minRows: 6, maxRows: 8 }"
          maxlength="56"
          show-word-limit
        />
      </el-form-item>
      <el-button type="primary" @click="onSubmit(userInfoFormRef)">
        更新信息
      </el-button>
    </el-form>
    <el-dialog
      v-model="isShow"
      width="40%"
      title="编辑头像"
      destroy-on-close
      :closeOnClickModal="false"
      :before-close="handleClose"
      :fullscreen="deviceDetection()"
    >
      <ReCropperPreview ref="cropRef" :imgSrc="imgSrc" @cropper="onCropper" />
      <template #footer>
        <div class="dialog-footer">
          <el-button bg text @click="handleClose">取消</el-button>
          <el-button bg text type="primary" @click="handleSubmitImage">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
